package com.wzcl.app.config.oauth.handler;

import com.alibaba.fastjson.JSON;
import com.wzcl.app.model.common.BusinessException;
import com.wzcl.app.model.common.RVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Log4j2
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        RVO error;
        if (exception instanceof BadCredentialsException ||
                exception instanceof UsernameNotFoundException) {
            error = new RVO(400,"账户名或者密码输入错误!");
        } else if (exception instanceof LockedException) {
            error = new RVO(401,"账户被禁用,请联系管理员!");
        } else if (exception instanceof CredentialsExpiredException) {
            error = RVO.error("密码过期,请联系管理员!");
        } else if (exception instanceof AccountExpiredException) {
            error = RVO.error("账户过期,请联系管理员!");
        } else if (exception instanceof DisabledException) {
            error = new RVO(403,"账户已注销,请联系管理员!");
        } else if (exception instanceof BusinessException){
            BusinessException businessException = (BusinessException) exception;
            error = new RVO(businessException.getCode(),businessException.getMessage());
        }else{
            error = RVO.error("登录失败");
        }
        response.setStatus(401);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(JSON.toJSONString(error));
        out.flush();
        out.close();
    }
}

